#!/usr/bin/env node

/**
 * 测试预约列表接口
 * 模拟前端调用，检查返回的数据数量
 */

import { existsSync } from 'node:fs'
import { dirname, join } from 'node:path'
import { fileURLToPath } from 'node:url'

const __filename = fileURLToPath(import.meta.url)
const __dirname = dirname(__filename)
const projectRoot = join(__dirname, '..')

async function main() {
  console.log('='.repeat(60))
  console.log('测试预约列表接口')
  console.log('='.repeat(60))
  console.log()

  // 初始化数据库 - 使用生产环境路径
  const { PrismaClient } = await import('@prisma/client')
  
  // 尝试多个可能的数据库路径（优先使用生产环境）
  const possibleDbPaths = []
  
  // 如果是Windows，优先使用生产环境路径
  if (process.platform === 'win32') {
    // 优先使用生产环境实际路径
    possibleDbPaths.push('C:\\Users\\Administrator\\AppData\\Roaming\\AutoTools\\data\\app.db')
    
    const appData = process.env.APPDATA || process.env.LOCALAPPDATA
    if (appData) {
      possibleDbPaths.push(join(appData, 'AutoTools', 'data', 'app.db'))
      possibleDbPaths.push(join(appData, 'auto-tools', 'data', 'app.db'))
    }
  }
  
  // 最后尝试开发环境路径
  possibleDbPaths.push(join(projectRoot, 'prisma', 'data', 'app.db'))
  
  let dbPath = null
  for (const path of possibleDbPaths) {
    if (existsSync(path)) {
      dbPath = path
      console.log(`找到数据库文件: ${dbPath}`)
      break
    }
  }
  
  if (!dbPath) {
    console.error('❌ 未找到数据库文件，尝试了以下路径:')
    possibleDbPaths.forEach(p => console.error(`  - ${p}`))
    process.exit(1)
  }
  
  const dbUrl = `file:${dbPath.replace(/\\/g, '/')}`
  process.env.DATABASE_URL = dbUrl

  const prisma = new PrismaClient({
    datasources: {
      db: { url: dbUrl },
    },
  })

  try {
    await prisma.$executeRawUnsafe('PRAGMA journal_mode=WAL;')
  }
  catch {}

  // 直接测试查询逻辑（模拟 getAppointmentsList 的行为）
  console.log('测试1: 不传递 is_placeholder (模拟前端传递 undefined)')
  console.log('----------------------------------------')
  const filters1 = {
    appointment_status: [],
    is_placeholder: undefined, // 模拟前端
  }
  // 模拟 JSON.stringify 的行为（会移除 undefined）
  const plainFilters1 = JSON.parse(JSON.stringify(filters1))
  console.log('序列化后的 filters:', JSON.stringify(plainFilters1, null, 2))
  
  const where1 = {}
  if (plainFilters1.is_placeholder !== undefined) {
    where1.is_placeholder = plainFilters1.is_placeholder
  }
  console.log('构建的 where 条件:', JSON.stringify(where1, null, 2))
  const result1 = await prisma.appointment_management.count({ where: where1 })
  console.log(`返回总数: ${result1}`)
  console.log()

  console.log('测试2: 明确传递 is_placeholder = false (普通预约)')
  console.log('----------------------------------------')
  const filters2 = {
    appointment_status: [],
    is_placeholder: false,
  }
  const where2 = {}
  if (filters2.is_placeholder !== undefined) {
    where2.is_placeholder = filters2.is_placeholder
  }
  const result2 = await prisma.appointment_management.count({ where: where2 })
  console.log(`返回总数: ${result2}`)
  console.log()

  console.log('测试3: 明确传递 is_placeholder = true (占号数据)')
  console.log('----------------------------------------')
  const filters3 = {
    appointment_status: [],
    is_placeholder: true,
  }
  const where3 = {}
  if (filters3.is_placeholder !== undefined) {
    where3.is_placeholder = filters3.is_placeholder
  }
  const result3 = await prisma.appointment_management.count({ where: where3 })
  console.log(`返回总数: ${result3}`)
  console.log()

  console.log('测试4: 空对象 filters (完全默认)')
  console.log('----------------------------------------')
  const filters4 = {}
  const where4 = {}
  if (filters4.is_placeholder !== undefined) {
    where4.is_placeholder = filters4.is_placeholder
  }
  const result4 = await prisma.appointment_management.count({ where: where4 })
  console.log(`返回总数: ${result4}`)
  console.log()

  // 直接查询数据库验证
  console.log('数据库直接查询验证:')
  console.log('----------------------------------------')
  const totalInDb = await prisma.appointment_management.count()
  const placeholderInDb = await prisma.appointment_management.count({
    where: { is_placeholder: true },
  })
  const normalInDb = await prisma.appointment_management.count({
    where: { is_placeholder: false },
  })
  const nullInDb = await prisma.appointment_management.count({
    where: { is_placeholder: null },
  })
  console.log(`数据库总记录数: ${totalInDb}`)
  console.log(`占号数据 (is_placeholder=true): ${placeholderInDb}`)
  console.log(`普通预约 (is_placeholder=false): ${normalInDb}`)
  console.log(`is_placeholder=null: ${nullInDb}`)
  console.log()

  console.log('='.repeat(60))
  console.log('结论:')
  console.log(`- 测试1 (undefined→移除): 应该返回 ${totalInDb} 条，实际返回 ${result1} 条`)
  console.log(`- 测试2 (false): 应该返回 ${normalInDb} 条，实际返回 ${result2} 条`)
  console.log(`- 测试3 (true): 应该返回 ${placeholderInDb} 条，实际返回 ${result3} 条`)
  console.log(`- 测试4 (空对象): 应该返回 ${totalInDb} 条，实际返回 ${result4} 条`)
  console.log('='.repeat(60))
  
  if (result1 === placeholderInDb) {
    console.log('\n⚠️  发现问题：测试1返回的是占号数据数量！')
    console.log('   这说明当 is_placeholder 字段不存在时，Prisma可能默认查询了占号数据')
    console.log('   或者数据库中大部分数据都是占号数据')
  }
  else if (result1 === totalInDb) {
    console.log('\n✅ 测试1正常：返回了所有数据')
    console.log('   接口逻辑正确，问题可能在前端默认过滤或UI显示')
  }
  else {
    console.log('\n⚠️  异常：测试1返回的数量不符合预期')
  }
  console.log()
}
finally {
  await prisma.$disconnect()
}

main().catch((e) => {
  console.error('脚本执行失败:', e)
  process.exit(1)
})

